#include "registerdialog.h"
#include "ui_registerdialog.h"
#include <QMessageBox>
#include <QRegularExpression>

RegisterDialog::RegisterDialog(UserDao *userDao, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::RegisterDialog),
    m_userDao(userDao)
{
    ui->setupUi(this);
    setWindowTitle("注册新用户");
    ui->lineEditPassword->setEchoMode(QLineEdit::Password);
    ui->lineEditConfirmPassword->setEchoMode(QLineEdit::Password);
    ui->labelError->hide();
}

RegisterDialog::~RegisterDialog()
{
    delete ui;
}

bool RegisterDialog::validateInput()
{
    QString username = ui->lineEditUsername->text().trimmed();
    QString password = ui->lineEditPassword->text();
    QString confirmPassword = ui->lineEditConfirmPassword->text();

    if (username.length() < 4 || username.length() > 20) {
        QMessageBox::warning(this, "输入错误", "用户名长度必须在4-20个字符之间");
        return false;
    }

    QRegularExpression regex("^[a-zA-Z0-9_]+$");
    if (!regex.match(username).hasMatch()) {
        QMessageBox::warning(this, "输入错误", "用户名只能包含字母、数字和下划线");
        return false;
    }

    if (password.length() < 6) {
        QMessageBox::warning(this, "输入错误", "密码长度至少为6个字符");
        return false;
    }

    if (password != confirmPassword) {
        QMessageBox::warning(this, "输入错误", "两次输入的密码不一致");
        return false;
    }

    if (m_userDao->isUsernameExist(username)) {
        QMessageBox::warning(this, "注册失败", "该用户名已被注册");
        return false;
    }

    return true;
}

void RegisterDialog::on_btnRegister_clicked()
{
    if (!validateInput()) {
        return;
    }

    QString username = ui->lineEditUsername->text().trimmed();
    QString password = ui->lineEditPassword->text();

    QString defaultRealName = username;
    if (m_userDao->registerUser(username, password, defaultRealName)) {
        QMessageBox::information(this, "注册成功", "注册成功，请登录！");
        accept();
    } else {
        ui->labelError->setText("注册失败: 数据库错误");
        ui->labelError->show();
    }
}

void RegisterDialog::on_btnCancel_clicked()
{
    reject();
}

QString RegisterDialog::getUsername() const
{
    return ui->lineEditUsername->text().trimmed();
}
